package com.lanou.dllo.baisibudejie.adapater;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.lanou.dllo.baisibudejie.R;
import com.lanou.dllo.baisibudejie.entity.MusicEntity;
import com.lanou.dllo.baisibudejie.music.Player;
import com.lanou.dllo.baisibudejie.view.CircleImage;
import com.lanou.dllo.baisibudejie.volley.VolleySingleton;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/23.
 */
public class MusicAdapter extends RecyclerView.Adapter<MusicAdapter.JokesViewHolder> {

    private Context context;
    private List<MusicEntity> datas;
    private RequestQueue queue;
    private Player player;
    private String minStr;
    private String secStr;
    private Handler handler;
    private int love_count;

    public MusicAdapter(Context c) {
        this.context = c;
        queue = Volley.newRequestQueue(c);
    }

    /**
     * 加载行布局
     *
     * @param parent
     * @param viewType
     * @return
     */
    @Override
    public JokesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.card_music_item, null);

        return new JokesViewHolder(view);
    }

    /**
     * 解析数据设置内容
     *
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(final JokesViewHolder holder, final int position) {


        if (datas.get(position) != null) {
            final MusicEntity listEntity = datas.get(position);
            player = new Player(holder.skbProgress);

            holder.music_item_loveIv.setVisibility(View.VISIBLE);
            holder.music_item_love_an_Iv.setVisibility(View.GONE);
            if (listEntity != null) {

                if (listEntity.getText() != null && listEntity.getText().length() > 0) {
                    holder.music_item_contentTv.setText(listEntity.getText());//设置内容
                }
                if (listEntity.getName() != null && listEntity.getName().length() > 0) {
                    holder.music_item_nameTv.setText(listEntity.getName());//设置姓名
                }
                if (listEntity.getCreated_at() != null && listEntity.getCreated_at().length() > 0) {
                    holder.music_item_timeTv.setText(listEntity.getCreated_at());//设置时间
                }

                if (listEntity.getLove() != null && listEntity.getLove().length() > 0) {
                    final String love = listEntity.getLove();
                    boolean isLoveClick = false;


                    holder.music_item_loveTv.setText(love);//点赞
                    holder.music_item_loveIv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            holder.isLoveClick = true;
                            love_count = Integer.parseInt(holder.music_item_loveTv.getText().toString()) + 1;
                            listEntity.setLove(love_count+"");
                            if (holder.isLoveClick) {
                                holder.music_item_loveTv.setText(love_count +"");
                                holder.music_item_loveIv.setVisibility(View.GONE);
                                holder.music_item_love_an_Iv.setVisibility(View.VISIBLE);

                            }
                        }
                    });
                    //判断是否点击
                    if (!holder.isLoveClick) {
                            holder.music_item_loveTv.setText(love);
                            holder.music_item_loveIv.setVisibility(View.VISIBLE);
                            holder.music_item_love_an_Iv.setVisibility(View.GONE);
                    }
                    if (holder.isLoveClick) {
                        holder.music_item_loveTv.setText(love);
                        holder.music_item_loveIv.setVisibility(View.GONE);
                        holder.music_item_love_an_Iv.setVisibility(View.VISIBLE);

                    }

                } else {
                    holder.music_item_loveTv.setText(0);
                }
                if (listEntity.getHate() != null && listEntity.getHate().length() > 0) {
                    holder.music_item_hateTv.setText(listEntity.getHate());//踩量
                } else {
                    holder.music_item_hateTv.setText(0);
                }
                if (listEntity.getProfile_image() != null && listEntity.getProfile_image().length() > 0) {
                    getCircleBitmap(listEntity.getProfile_image(), holder.music_item_headIconIv);//头像
                }
                if (listEntity.getImage0() != null && listEntity.getImage0().length() > 0) {//图片
                    getBitmap(listEntity.getImage0(), holder.music_item_imageIv);
                }
                if (listEntity.getRepost() != null && listEntity.getRepost().length() > 0) {//分享量
                    holder.music_item_repostTv.setText(listEntity.getRepost());
                } else {
                    holder.music_item_repostTv.setText(0);
                }
                if (listEntity.getComment() != null && listEntity.getComment().length() > 0) {//评论量
                    holder.music_item_commentTv.setText(listEntity.getComment());
                } else {
                    holder.music_item_commentTv.setText(0);
                }
                if (listEntity.getVoiceuri() != null && listEntity.getVoiceuri().length() > 0) {//音乐路径
//                    musicUrl = listEntity.getVoiceuri();


                    holder.stopIv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            holder.pauseIv.setVisibility(View.GONE);
//                            holder.playUrlIv.setVisibility(View.VISIBLE);
                                player.stop();
                        }
                    });
                    holder.music_item_imageIv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            holder.playUrlIv.setVisibility(View.GONE);
//                            holder.pauseIv.setVisibility(View.VISIBLE);
                            player.playUrl(listEntity.getVoiceuri());
                        }
                    });
                }
                if (listEntity.getVoicetime() != null && listEntity.getVoicetime().length() > 0) {

                    String musicTime = listEntity.getVoicetime();
                    int time = Integer.parseInt(musicTime);
                    int min = time / 60;
                    int sec = (time - (min * 60));
                    if ((min < 0)) {
                        minStr = "0" + min;
                    } else {
                        minStr = "" + min;
                    }
                    if ((sec < 0)) {
                        secStr = "0" + sec;
                    } else {
                        secStr = "" + sec;
                    }
                    holder.musicTimeTv.setText(minStr + ":" + secStr);
                }

            }
        }


    }

    @Override
    public int getItemCount() {
        return datas != null && datas.size() > 0 ? datas.size() : 0;
    }


    /**
     * 组件缓存内部类
     */
    class JokesViewHolder extends RecyclerView.ViewHolder {

        private TextView music_item_contentTv;//内容
        private TextView music_item_nameTv;//姓名
        private TextView music_item_timeTv;//时间
        private TextView music_item_loveTv;//点赞量
        private TextView music_item_hateTv;//踩量
        private ImageView music_item_headIconIv;//头像
        private TextView music_item_repostTv;//转发量
        private TextView music_item_commentTv;//评论量
        private NetworkImageView music_item_imageIv;//图片
        //        private ImageView playUrlIv;
        private ImageView stopIv;
        private TextView musicTimeTv;
        private SeekBar skbProgress;
        private ImageView music_item_loveIv, music_item_love_an_Iv;
        private boolean isLoveClick;


        public JokesViewHolder(View v) {
            super(v);
            music_item_contentTv = (TextView) v.findViewById(R.id.music_item_contentTv);
            music_item_nameTv = (TextView) v.findViewById(R.id.music_item_nameTv);
            music_item_timeTv = (TextView) v.findViewById(R.id.music_item_timeTv);
            music_item_loveTv = (TextView) v.findViewById(R.id.music_item_loveTv);
            music_item_hateTv = (TextView) v.findViewById(R.id.music_item_hateTv);
            music_item_headIconIv = (ImageView) v.findViewById(R.id.music_item_headIconIv);
            music_item_repostTv = (TextView) v.findViewById(R.id.music_item_repostTv);
            music_item_commentTv = (TextView) v.findViewById(R.id.music_item_commentTv);
            music_item_imageIv = (NetworkImageView) v.findViewById(R.id.music_item_imageIv);
            musicTimeTv = (TextView) v.findViewById(R.id.musicTimeTv);
            stopIv = (ImageView) v.findViewById(R.id.stopIv);
//            playUrlIv = (ImageView) v.findViewById(R.id.playUrlIv);
            skbProgress = (SeekBar) v.findViewById(R.id.skbProgress);
            skbProgress.setVisibility(View.GONE);
            music_item_loveIv = (ImageView) v.findViewById(R.id.music_item_loveIv);
            music_item_love_an_Iv = (ImageView) v.findViewById(R.id.music_item_love_an_Iv);
            isLoveClick = false;

        }


    }

    public void addData(List<MusicEntity> data) {
        this.datas = data;
        notifyDataSetChanged();//数据改变 页面刷新
    }

    private void getBitmap(String url, final NetworkImageView networkImageView) {
        ImageLoader imageLoader = VolleySingleton.getInstance().getImageLoader();
        networkImageView.setDefaultImageResId(R.mipmap.cleak_repeat_normal);
        networkImageView.setErrorImageResId(R.mipmap.cleak_repeat_normal);
        networkImageView.setImageUrl(url, imageLoader);


    }

    private void getCircleBitmap(String url, final ImageView imageView) {

        ImageRequest request = new ImageRequest(url,
                new Response.Listener<Bitmap>() {

                    @Override
                    public void onResponse(Bitmap response) {
                        int radius;
                        // 将返回的bitmap图片对象设置到图片组件中
                        if (response.getWidth() <= response.getHeight()) {
                            radius = response.getWidth() / 2;
                        } else {
                            radius = response.getHeight() / 2;
                        }

                        Bitmap circleImage = new CircleImage(context).getCroppedRoundBitmap(response, radius);
                        imageView.setImageBitmap(circleImage);


                    }
                },
                0, 0, Bitmap.Config.ARGB_8888,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO Auto-generated method stub
                        error.printStackTrace();
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                // TODO Auto-generated method stub
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.add(request);//将本次图片请求加入到请求队列中
    }

    private void getBitmap(String url, final ImageView imageView) {

        ImageRequest request = new ImageRequest(url,
                new Response.Listener<Bitmap>() {

                    @Override
                    public void onResponse(Bitmap response) {


                        imageView.setImageBitmap(response);
                    }
                },
                0, 0, Bitmap.Config.ARGB_8888,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO Auto-generated method stub
                        error.printStackTrace();
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                // TODO Auto-generated method stub
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.add(request);//将本次图片请求加入到请求队列中
    }


}


